import wx from '../../subwe/bridge';
import WXPage from "../../subwe/page";
const app = getApp();
import CONST from '../../utils/const';
import { BluetoothMac, BluetoothPowerMinute } from '../../utils/util';
import { BLEConnectionMessage, openBluetoothAdapter, openBluetoothAdapterPeripheral, connectBluetoothRecharge } from '../../utils/bluetooth';
import { Index } from '../../apis/index';
const API = new Index();
let bluetoothStatusTime = null;
function inArray(arr, key, val) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i][key] === val) {
      return i;
    }
  }
  return -1;
}
WXPage({
  data: {
    devices: [],
    connected: false,
    chs: [],
    system: wx.getSystemInfoSync(),
    tradeNo: '',
    deviceSn: '',
    // 蓝牙相关
    CONST,
    powerMinute: 0,
    // 通电时长：分钟
    bluetoothMac: '',
    bluetoothErrNum: 0,
    bluetoothExist: false,
    bluetoothStatus: CONST.BluetoothStatusSearch,
    bluetoothOrderStatus: CONST.BluetoothOrderStatusNotPayment,
    bluetoothShowError: 2,
    showAd: 1,
    isChangeSuccess: false,
    informLoading: false // 通知加载中
  },

  server: null,
  onLoad(options) {
    // let options = getCurrentPages()[0]
    options = {
      options
    };
    console.log('system', this.data.system, options);
    console.log(options.options.bluetoothMac);
    this.setData({
      tradeNo: options.options.tradeNo || ''
    });
    this.setData({
      deviceSn: options.options.deviceSn || ''
    });
    this.setData({
      showAd: wx.getStorageSync("showAd")
    });
    this.setData({
      bluetoothMac: options.options.bluetoothMac || ''
    });
    this.setData({
      powerMinute: Number(options.options.powerMinute) || 0
    });
    this.setData({
      bluetoothOrderStatus: Number(options.options.status) || CONST.BluetoothOrderStatusNotPayment
    });
    this.setData({
      bluetoothShowError: Number(options.options.showErr) || 2
    });
    if (this.data.bluetoothShowError !== 1) {
      bluetoothStatusTime = setTimeout(() => this.setBluetoothStatus(CONST.BluetoothStatusFail), 8500);
      this.openBluetoothAdapter();
    } else this.setBluetoothStatus(CONST.BluetoothStatusFail);

    // // 在页面中定义插屏广告
    // let interstitialAd = null

    // // 在页面onLoad回调事件中创建插屏广告实例
    // if (wx.createInterstitialAd) {
    //     interstitialAd = wx.createInterstitialAd({
    //         adUnitId: 'adunit-69f9f9a254f71449'
    //     })
    //     interstitialAd.onLoad(() => {})
    //     interstitialAd.onError((err) => {})
    //     interstitialAd.onClose(() => {})
    // }

    // // 在适合的场景显示插屏广告
    // if (interstitialAd) {
    //     interstitialAd.show().catch((err) => {
    //         console.error(err)
    //     })
    // }
  },

  // 蓝牙连接模式充电
  connectBluetoothRechargeFn() {
    const {
      deviceSn,
      bluetoothMac,
      powerMinute
    } = this.data;
    openBluetoothAdapterPeripheral({
      deviceSn,
      bluetoothMac,
      powerMinute,
      success: res => {
        console.log('startAdvertising', res);
        this.setBluetoothStatus(CONST.BluetoothStatusInform);
        this.addBluetoothRechargeLog();
      },
      fail: err => {
        this.setBluetoothStatus(CONST.BluetoothStatusFail);
      }
    });
    // const { deviceSn, bluetoothMac, powerMinute } = this.data
    // const param = { deviceSn, bluetoothMac, powerMinute }
    // connectBluetoothRecharge({
    //     ...param,
    //     success: res => {
    //         console.log('connectBluetoothRechargeFn-success', res)
    //         this.setBluetoothStatus(CONST.BluetoothStatusInform)
    //     },
    //     fail: err => {
    //         console.log('connectBluetoothRechargeFn-err', err)
    //         this.setBluetoothStatus(CONST.BluetoothStatusFail)
    //     }
    // })
  },

  // 跳转至订单详情
  toOrderList: function () {
    wx.navigateTo({
      url: `/pages/mine/orderdetail/orderdetail?tradeNo=${this.data.tradeNo}&deviceSn=${app.globalData.deviceSn}`
    });
  },
  addBluetoothRechargeLog() {
    let {
      tradeNo,
      powerMinute
    } = this.data;
    let model = app.globalData.systemInfo.model;
    let system = app.globalData.systemInfo.system;
    let deviceSn = app.globalData.deviceSn;
    let params = {
      tradeNo,
      duration: powerMinute,
      model,
      system,
      deviceSn,
      status: 1,
      type: 1
    };
    API.addBluetoothRechargeLog(params).then(res => {
      console.log(res);
    });
  },
  // 初始化蓝牙 主机模式
  openBluetoothAdapter() {
    if (this.data.informLoading) return
    this.data.informLoading = true
    this.openBluetoothAdapterPeripheral()
  },

  // 初始化蓝牙 外围模式
  openBluetoothAdapterPeripheral() {
    openBluetoothAdapterPeripheral({
      bluetoothMac: this.data.bluetoothMac,
      powerMinute: this.data.powerMinute,
      success: res => {
        console.log('startAdvertising', res);
        this.setBluetoothStatus(CONST.BluetoothStatusInform);
        this.addBluetoothRechargeLog();
      },
      fail: err => {
        this.setBluetoothStatus(CONST.BluetoothStatusFail);
      }
    });
  },

  // 设置蓝牙状态
  setBluetoothStatus(status) {
    if (status === CONST.BluetoothStatusFail || status === CONST.BluetoothStatusInform) this.data.informLoading = false;
    clearTimeout(bluetoothStatusTime);
    this.setData({
      bluetoothStatus: status
    });
    if (status === CONST.BluetoothStatusFail) this.setData({
      bluetoothErrNum: this.data.bluetoothErrNum + 1
    });
  },
  // 手动重新连接
  reconnectionBluetooth() {
    this.setBluetoothStatus(CONST.BluetoothStatusSearch);
    clearTimeout(bluetoothStatusTime);
    bluetoothStatusTime = setTimeout(() => this.setBluetoothStatus(CONST.BluetoothStatusFail), 8500);
    setTimeout(this.openBluetoothAdapter.bind(this), 100);
  },
  // 使用密码充电
  toPagePassword() {
    wx.redirectTo({
      url: '/pages/result/result?tradeno=' + this.data.tradeNo
    });
  },
  // 恢复充电
  RecoveringCharge() {
    this.openBluetoothAdapterPeripheral();
  }
});
